package com.hxiaoyi.cloud.service;

import cn.hutool.core.util.IdUtil;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.concurrent.TimeUnit;

/**
 * PaymentService
 * @author 黄敬意
 * @date 2022-02-09 21:33
 **/
@Service
public class PaymentService {

    /**
     * 正常访问 ok
     * @param id
     * @return
     */
    public String paymentInfo_OK(Integer id){
        return "线程池： " + Thread.currentThread().getName() + "paymentInfo_OK, id:" + id + "\t" + "哈哈额~~";
    }
    /**
     * 超时
     * @param id
     * @return
     * HystrixCommand设置出错后兜底的方法，HystrixProperty设置超过这个时间内的就调用兜底方法
     */
    @HystrixCommand(fallbackMethod = "paymentTimeoutHandler", commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "2000")
    })
    public String paymentInfo_TimeOut(Integer id){
        //int time = 10/0;
        int time = 1000;
        try {
            /**耗时几毫秒钟*/
            TimeUnit.MILLISECONDS.sleep(time); } catch (InterruptedException e) { e.printStackTrace(); }
        return "线程池： " + Thread.currentThread().getName() + "paymentInfo_TimeOut, id:" + id + "\t" + "哈哈额~~";
    }

    /**
     * Hystrix出错兜底方法
     * @param id
     * @return
     */
    public String paymentTimeoutHandler(Integer id){
        return "线程池： " + Thread.currentThread().getName() + "paymentTimeoutHandler, id:" + id + "\t" + "系统繁忙稍后再试！" + "/(ㄒoㄒ)/~~";
    }

    /**
     * 服务熔断
     * @param id
     * @return String
     */
    @HystrixCommand(fallbackMethod = "paymentCircuitBreaker_fallback", commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled", value = "true"),//是否开启断路器
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),//请求次数
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"),//时间窗口期
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60"),//失败率达到多少后调用兜底方法
    })
    public String paymentCircuitBreaker(@PathVariable("id") Integer id){
        if (id < 0){
            throw new RuntimeException("--------id不能为负数" + id);
        }
        String number = IdUtil.simpleUUID();
        return Thread.currentThread().getName() + "\t" + "调用成功，流水号为：" + number;
    }

    /**
     * 服务熔断
     * @param id
     * @return String
     */
    public String paymentCircuitBreaker_fallback(@PathVariable("id") Integer id){
        return "id不能为负数，请稍后再试： " + id + "---/(ㄒoㄒ)/~~";
    }
}
